const express = require('express');
const session = require('express-session');
const app = express();
const path = require('path');
const todoListModel = require('./db/model/todoListModel');
// 支持post数据
app.use(express.urlencoded({extended:false}));
// 支持session
app.use(session({
    secret: 'atguigu', 
    saveUninitialized: false,
    resave: false ,
    cookie:{
        maxAge:1000 * 60 * 60 * 24 * 15
    }
}));
// 支持ejs
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

// 设置静态资源
app.use(express.static(path.resolve(__dirname, './public')));

app.get('/index', (req, res)=>{
    todoListModel.find({}).sort({_id:-1}).then(todoList=>{
        // console.log('todoList: ', todoList);
        res.render('index', {todoList});
    })
})

app.post('/addTodo', (req,res)=>{
    let {title} = req.body;
    todoListModel.create({title}).then(todo=>{
        // 添加成功后重定向到index路由，获取最新的列表数据并渲染
        res.redirect('/index');
    })
})

// 根据id删除数据
app.get('/delete', (req, res)=>{
    // query参数
    let {_id} = req.query;
    todoListModel.deleteOne({_id}).then(data=>{
        res.redirect('/index');
    })
})
// params 参数 path参数  必须要有占位符
app.get('/delete/:_id', (req, res)=>{
    let {_id} = req.params;
    todoListModel.deleteOne({_id}).then(data=>{
        res.redirect('/index');
    })
})

app.listen(8080, ()=>{
    console.log('server run at 8080');
})